package com.gene.tlonpo.util;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @author genex
 * 基于kryo的序列化工具
 */
public class KryoSerializerUtil {
    //序列化
    public static byte[] serializer(Object obj) {
        Kryo kryo = local.get();
        ByteArrayOutputStream outputSteam = new ByteArrayOutputStream();
        Output output = new Output(outputSteam);

        kryo.writeClassAndObject(output, obj);

        output.close();

        return outputSteam.toByteArray();
    }

    public static <T> T deserializer(byte[] bytes, Class<T> clazz) {
        Kryo kryo = local.get();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        Input input = new Input(inputStream);
        input.close();
        return clazz.cast(kryo.readClassAndObject(input));
        //return (T)kryo.readClassAndObject(input);
    }


    private static ThreadLocal<Kryo> local = ThreadLocal.withInitial(() -> {
        Kryo kryo = new Kryo();
        kryo.setRegistrationRequired(false);
        kryo.setReferences(true);
        return kryo;

    });


}
